<!-- src/components/BatchImportDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    title="批量导入图书"
    width="600px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <el-alert
      title="导入说明"
      type="info"
      description="请下载模板文件，按照格式填写后上传。支持.xlsx格式文件。"
      show-icon
      style="margin-bottom: 20px;"
    />

    <el-button
      type="primary"
      size="small"
      @click="downloadTemplate"
      icon="Download"
      style="margin-bottom: 20px;"
    >
      下载模板
    </el-button>

    <el-upload
      ref="uploadRef"
      drag
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :on-remove="handleFileRemove"
      :file-list="fileList"
      accept=".xlsx,.xls"
      :limit="1"
      :on-exceed="handleExceed"
    >
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          只能上传xlsx/xls文件，且不超过10MB
        </div>
      </template>
    </el-upload>

    <!-- 预览表格 -->
    <div v-if="previewData.length > 0" class="preview-section">
      <h4 style="margin: 20px 0 10px 0;">数据预览 ({{ previewData.length }} 条)</h4>
      <el-table
        :data="previewData"
        height="300"
        style="width: 100%"
        size="small"
      >
        <el-table-column prop="isbn" label="ISBN" width="180" />
        <el-table-column prop="title" label="书名" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="genre" label="分类" width="100" />
        <el-table-column prop="publicationDate" label="出版日期" width="120" />
        <el-table-column prop="totalCopies" label="总数量" width="80" align="center" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.valid ? 'success' : 'danger'"
              size="small"
            >
              {{ scope.row.valid ? '有效' : '无效' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleImport"
          :loading="importing"
          :disabled="previewData.length === 0 || !hasValidData"
        >
          确认导入
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, defineExpose } from 'vue'
import * as XLSX from 'xlsx'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import { saveAs } from 'file-saver'

export default {
  name: 'BatchImportDialog',
  components: {
    UploadFilled,
    // eslint-disable-next-line vue/no-unused-components
    Download
  },
  setup() {
    const visible = ref(false)
    const uploadRef = ref(null)
    const fileList = ref([])
    const previewData = ref([])
    const importing = ref(false)

    // 模板数据
    const templateData = [
      {
        ISBN: '978-0-123456-78-9',
        书名: '示例图书名称',
        作者: '作者姓名',
        分类: '编程',
        出版日期: '2023-01-15',
        总数量: 5
      }
    ]

    const show = () => {
      visible.value = true
      resetState()
    }

    const resetState = () => {
      fileList.value = []
      previewData.value = []
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
    }

    const handleClose = () => {
      visible.value = false
      resetState()
    }

    const downloadTemplate = () => {
      // 创建模板Excel文件
      const ws = XLSX.utils.json_to_sheet(templateData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, '图书模板')

      // 转换为blob并下载
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([wbout], { type: 'application/octet-stream' })
      saveAs(blob, '图书导入模板.xlsx')
    }

    const validateRow = (row) => {
      const errors = []

      // ISBN验证
      if (!row.isbn || row.isbn.toString().trim() === '') {
        errors.push('ISBN不能为空')
      } else if (row.isbn.toString().length < 10 || row.isbn.toString().length > 20) {
        errors.push('ISBN长度应在10-20字符之间')
      }

      // 书名验证
      if (!row.title || row.title.toString().trim() === '') {
        errors.push('书名不能为空')
      } else if (row.title.toString().length > 100) {
        errors.push('书名长度不能超过100字符')
      }

      // 作者验证
      if (!row.author || row.author.toString().trim() === '') {
        errors.push('作者不能为空')
      } else if (row.author.toString().length > 50) {
        errors.push('作者名长度不能超过50字符')
      }

      // 分类验证
      const validGenres = ['文学', '小说', '编程', '历史', '科学', '艺术', '其他']
      if (!row.genre || !validGenres.includes(row.genre.toString().trim())) {
        errors.push('分类必须是: ' + validGenres.join(', '))
      }

      // 出版日期验证
      if (!row.publicationDate) {
        errors.push('出版日期不能为空')
      } else {
        const date = new Date(row.publicationDate)
        if (isNaN(date.getTime())) {
          errors.push('出版日期格式无效')
        } else if (date > new Date()) {
          errors.push('出版日期不能是未来日期')
        }
      }

      // 总数量验证
      if (row.totalCopies === undefined || row.totalCopies === null) {
        errors.push('总数量不能为空')
      } else if (typeof row.totalCopies !== 'number' || row.totalCopies < 1 || row.totalCopies > 1000) {
        errors.push('总数量必须是1-1000之间的数字')
      }

      return {
        valid: errors.length === 0,
        errors: errors
      }
    }

    const handleFileChange = (file) => {
      console.log('文件已选择:', file)

      // 重置预览数据
      previewData.value = []

      // 读取Excel文件
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })

          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]

          // 转换为JSON
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

          if (jsonData.length === 0) {
            ElMessage.error('Excel文件为空')
            return
          }

          // 获取表头（第一行）
          const headers = jsonData[0]
          console.log('Excel表头:', headers)

          // 验证表头
          const expectedHeaders = ['ISBN', '书名', '作者', '分类', '出版日期', '总数量']
          const headerMap = {}

          // 创建表头映射（支持中英文）
          headers.forEach((header, index) => {
            const headerStr = header.toString().trim()
            if (expectedHeaders.includes(headerStr)) {
              headerMap[headerStr] = index
            }
          })

          if (Object.keys(headerMap).length < expectedHeaders.length) {
            ElMessage.error('Excel文件格式不正确，请使用模板文件')
            return
          }

          // 解析数据行
          const parsedData = []
          for (let i = 1; i < jsonData.length; i++) {
            const row = jsonData[i]
            if (row.length === 0) continue // 跳过空行

            const bookData = {
              isbn: row[headerMap['ISBN']],
              title: row[headerMap['书名']],
              author: row[headerMap['作者']],
              genre: row[headerMap['分类']],
              publicationDate: row[headerMap['出版日期']],
              totalCopies: row[headerMap['总数量']]
            }

            // 验证数据
            const validation = validateRow(bookData)
            parsedData.push({
              ...bookData,
              valid: validation.valid,
              errors: validation.errors,
              rowIndex: i + 1
            })
          }

          previewData.value = parsedData
          console.log('解析完成的数据:', parsedData)

          if (parsedData.length === 0) {
            ElMessage.warning('未找到有效数据')
          } else {
            const validCount = parsedData.filter(item => item.valid).length
            ElMessage.success(`成功解析 ${parsedData.length} 条数据，其中 ${validCount} 条有效`)
          }

        } catch (error) {
          console.error('解析Excel文件失败:', error)
          ElMessage.error('解析Excel文件失败，请检查文件格式')
        }
      }

      reader.readAsArrayBuffer(file.raw)
    }

    const handleFileRemove = () => {
      previewData.value = []
    }

    const handleExceed = () => {
      ElMessage.warning('只能上传一个文件')
    }

    const hasValidData = () => {
      return previewData.value.some(item => item.valid)
    }

    const handleImport = async () => {
      try {
        const validData = previewData.value.filter(item => item.valid)
        if (validData.length === 0) {
          ElMessage.warning('没有有效的数据可以导入')
          return
        }

        await ElMessageBox.confirm(
          `确认导入 ${validData.length} 条有效数据吗？`,
          '导入确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        importing.value = true

        // 这里调用批量导入API（预留后端接口）
        const result = await importBooksBatch(validData)

        ElMessage.success(`批量导入成功！成功导入 ${result.successCount} 条，失败 ${result.failureCount} 条`)
        visible.value = false

        // 触发父组件刷新
        this.$emit('import-success')

      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量导入失败:', error)
          ElMessage.error('批量导入失败: ' + (error.message || '未知错误'))
        }
      } finally {
        importing.value = false
      }
    }

    // 预留后端API调用方法
    const importBooksBatch = async (booksData) => {
      // Mock实现 - 实际项目中这里会调用后端API
      console.log('准备批量导入数据:', booksData)

      return new Promise((resolve) => {
        setTimeout(() => {
          // 模拟部分成功部分失败
          const successCount = Math.floor(booksData.length * 0.9) // 90%成功率
          const failureCount = booksData.length - successCount

          resolve({
            successCount,
            failureCount,
            failures: booksData.slice(successCount).map((book) => ({
              rowIndex: book.rowIndex,
              error: '模拟导入失败'
            }))
          })
        }, 1000)
      })
    }

    defineExpose({
      show
    })

    return {
      visible,
      uploadRef,
      fileList,
      previewData,
      importing,
      show,
      handleClose,
      downloadTemplate,
      handleFileChange,
      handleFileRemove,
      handleExceed,
      hasValidData,
      handleImport
    }
  }
}
</script>

<style scoped>
.preview-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>